package zdh.avatar.gui;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import zdh.avatar.*;
import zdh.avatar.base.*;

/**
 *
 * @author Gem Seeker
 */
@SuppressWarnings("serial")
public class AddEditButton extends JFrame implements ActionListener {

    public static final byte ADD = 0x0;
    public static final byte EDIT = 0x1;
    private byte state;
    private MainFrame main;
    private ElementButton oldButton;
    private ElementButton newButton;
    private ElementPanel panel;
    private String buttonsPath;
    private String panelsPath;

    public AddEditButton(MainFrame main, AvatarConfig config, byte state, ElementButton button) {
        this.main = main;
        this.state = state;

        buttonsPath = config.getElementsPath() + "buttons/";
        panelsPath = config.getElementsPath() + "panels/";

        oldButton = button;

        initComponents();
        setComponents();
        initListeners();

        this.getRootPane().setDefaultButton(btn_save);
    }

    private void setComponents() {
        ElementPanel[] panels = ElementLoader.getElementPanels(panelsPath);
        if(panels != null){
            for (ElementPanel p : panels) {
                combo_panels.addItem(p);
            }
        }

        if (state == EDIT) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    tf_name.setText(oldButton.getButtonName());
                    tf_color.setBackground(oldButton.getButtonColor());

                    String[] audioPaths = oldButton.getAudioPaths();
                    tf_audioPath1.setText(audioPaths[0]);

                    if (audioPaths.length >= 2 && audioPaths[1] != null) {
                        cb_1.setSelected(true);
                        enableGroup(1);
                        tf_audioPath2.setText(audioPaths[1]);
                    }

                    if (audioPaths.length >= 3 && audioPaths[2] != null) {
                        cb_2.setSelected(true);
                        enableGroup(2);
                        tf_audioPath3.setText(audioPaths[2]);
                    }
                    
                    String buttonsPanel = oldButton.getPanelName();
                    for(int i=0; i<combo_panels.getItemCount(); i++){
                        if(combo_panels.getItemAt(i).toString().equals(buttonsPanel)){
                            combo_panels.setSelectedIndex(i);
                            break;
                        }
                    }
                }
            });
        }
    }

    private void initListeners() {
        btn_choose.addActionListener(this);
        btn_browse1.addActionListener(this);
        btn_browse2.addActionListener(this);
        btn_browse3.addActionListener(this);
        btn_save.addActionListener(this);
        btn_cancel.addActionListener(this);
        cb_1.addActionListener(this);
        cb_2.addActionListener(this);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                main.setEnabled(true);
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();

        if (source == btn_browse1) {
            String browsedDir = main.getCurrentBrowsedDir();
            JFileChooser fc = new JFileChooser(browsedDir);
            fc.setFileFilter(new AudioFileFilter());

            int action = fc.showOpenDialog(this);

            if (action == JFileChooser.APPROVE_OPTION) {
                tf_audioPath1.setText(fc.getSelectedFile().getAbsolutePath());
                main.setCurrentBrowsedDir(fc.getSelectedFile().getPath());
            }
        } else if (source == btn_browse2) {
            String browsedDir = main.getCurrentBrowsedDir();
            JFileChooser fc = new JFileChooser(browsedDir);
            fc.setFileFilter(new AudioFileFilter());

            int action = fc.showOpenDialog(this);

            if (action == JFileChooser.APPROVE_OPTION) {
                tf_audioPath2.setText(fc.getSelectedFile().getAbsolutePath());
                main.setCurrentBrowsedDir(fc.getSelectedFile().getPath());
            }
        } else if (source == btn_browse3) {
            String browsedDir = main.getCurrentBrowsedDir();
            JFileChooser fc = new JFileChooser(browsedDir);
            fc.setFileFilter(new AudioFileFilter());

            int action = fc.showOpenDialog(this);

            if (action == JFileChooser.APPROVE_OPTION) {
                tf_audioPath3.setText(fc.getSelectedFile().getAbsolutePath());
                main.setCurrentBrowsedDir(fc.getSelectedFile().getPath());
            }
        } else if (source == btn_choose) {
            Color col = JColorChooser.showDialog(this, "Select Button Color", tf_color.getBackground());
            tf_color.setBackground(col);
        } else if (source == btn_save) {
            StringBuilder str = new StringBuilder();
            str.append("ERROR:\n");
            
            boolean error = false;
            
            if (tf_name.getText().equals("")) {
                str.append("Invalid Button Name\n");
                tf_name.selectAll();
                tf_name.requestFocusInWindow();
                error = true;
            }

            ArrayList<String> paths = new ArrayList<>();

            String path1 = tf_audioPath1.getText();
            if (path1.equals("")) {
                str.append("Invalid audio path found (1)\n");
                tf_audioPath1.selectAll();
                tf_audioPath1.requestFocusInWindow();
                error = true;
            } else {
                paths.add(path1);
            }

            if (cb_1.isSelected()) {
                String path2 = tf_audioPath2.getText();
                if (path2.equals("")) {
                    str.append("Invalid audio path found (2)\n");
                    tf_audioPath2.selectAll();
                    tf_audioPath2.requestFocusInWindow();
                    error = true;
                } else {
                    paths.add(path2);
                }
            }

            if (cb_2.isSelected()) {
                String path3 = tf_audioPath3.getText();
                if (path3.equals("")) {
                    str.append("Invalid audio path found (3)\n");
                    tf_audioPath3.selectAll();
                    tf_audioPath3.requestFocusInWindow();
                    error = true;
                } else {
                    paths.add(path3);
                }
            }
            
            panel = (ElementPanel)combo_panels.getSelectedItem();
            if(newButton == null){
                int index = 0;
                if(state == EDIT){
                    index = oldButton.getButtonIndex();
                }else{
                    if(main.getButtonCount() >= 0){
                        index = main.getButtonCount() + 1;
                    }else{
                        index = 0;
                    }
                
                }
                
                newButton = new ElementButton(tf_name.getText(), tf_color.getBackground(),
                        paths.toArray(new String[paths.size()]), panel.getPanelName(),
                        index);
            }

            if(!error){
//                newButton = new ElementButton(tf_name.getText(),
//                        tf_color.getBackground(),
//                        paths.toArray(new String[paths.size()]),
//                        panel.getPanelName());
                
                if (state == ADD) {
                    boolean added = ElementLoader.addElementButton(newButton, buttonsPath, false);
                    if (!added) { // means button already exist
                        JOptionPane.showMessageDialog(this, "Button already exist.");
                        tf_name.selectAll();
                        tf_name.requestFocusInWindow();
                    } else {
                        main.loadButtons();
                        closeWindow();
                    }
                } else if (state == EDIT) {
                    ElementLoader.replaceElementButton(oldButton, newButton, buttonsPath);
                    main.loadButtons();
                    closeWindow();
                } else {
                    closeWindow();
                }
                
            }else{
                JOptionPane.showMessageDialog(this, str.toString(), "ERROR", JOptionPane.ERROR_MESSAGE);
            }
        } else if (source == btn_cancel) {
            closeWindow();
        } else if (source == cb_1) {
            if (cb_1.isSelected()) {
                enableGroup(1);
            } else {
                disableGroup(1);
            }
        } else if (source == cb_2) {
            if (cb_2.isSelected()) {
                enableGroup(2);
            } else {
                disableGroup(2);
            }
        }
    }

    private void enableGroup(int groupNo) {
        if (groupNo == 1) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    lbl_audioPath2.setEnabled(true);
                    tf_audioPath2.setEnabled(true);
                    btn_browse2.setEnabled(true);
                }
            });
        } else if (groupNo == 2) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    lbl_audioPath3.setEnabled(true);
                    tf_audioPath3.setEnabled(true);
                    btn_browse3.setEnabled(true);
                }
            });
        }
    }

    private void disableGroup(int groupNo) {
        if (groupNo == 1) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    lbl_audioPath2.setEnabled(false);
                    tf_audioPath2.setEnabled(false);
                    btn_browse2.setEnabled(false);
                }
            });
        } else if (groupNo == 2) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    lbl_audioPath3.setEnabled(false);
                    tf_audioPath3.setEnabled(false);
                    btn_browse3.setEnabled(false);
                }
            });
        }
    }

    public void showWindow() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                main.setEnabled(false);
                setLocationRelativeTo(null);
                setVisible(true);
            }
        });
    }

    public void closeWindow() {
        main.setEnabled(true);
        dispose();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated by Netbeans">
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbl_color = new javax.swing.JLabel();
        lbl_name = new javax.swing.JLabel();
        tf_color = new javax.swing.JTextField();
        tf_name = new javax.swing.JTextField();
        btn_choose = new javax.swing.JButton();
        btn_cancel = new javax.swing.JButton();
        btn_save = new javax.swing.JButton();
        lbl_audioPath1 = new javax.swing.JLabel();
        tf_audioPath1 = new javax.swing.JTextField();
        btn_browse1 = new javax.swing.JButton();
        btn_browse2 = new javax.swing.JButton();
        tf_audioPath2 = new javax.swing.JTextField();
        lbl_audioPath2 = new javax.swing.JLabel();
        cb_1 = new javax.swing.JCheckBox();
        btn_browse3 = new javax.swing.JButton();
        lbl_audioPath3 = new javax.swing.JLabel();
        cb_2 = new javax.swing.JCheckBox();
        tf_audioPath3 = new javax.swing.JTextField();
        jSeparator2 = new javax.swing.JSeparator();
        jSeparator3 = new javax.swing.JSeparator();
        lbl_group = new javax.swing.JLabel();
        combo_panels = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Edit Button");

        lbl_color.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lbl_color.setText("Button Color:");

        lbl_name.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lbl_name.setText("Button Name:");

        tf_color.setEditable(false);

        btn_choose.setText("Choose Color...");

        btn_cancel.setText("Cancel");

        btn_save.setText("Save");

        lbl_audioPath1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lbl_audioPath1.setText("Audio Path 1:");

        btn_browse1.setText("Browse");

        btn_browse2.setText("Browse");
        btn_browse2.setEnabled(false);

        tf_audioPath2.setEnabled(false);

        lbl_audioPath2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lbl_audioPath2.setText("Audio Path 2:");
        lbl_audioPath2.setEnabled(false);

        btn_browse3.setText("Browse");
        btn_browse3.setEnabled(false);

        lbl_audioPath3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lbl_audioPath3.setText("Audio Path 3:");
        lbl_audioPath3.setEnabled(false);

        tf_audioPath3.setEnabled(false);

        lbl_group.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lbl_group.setText("Button Group:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btn_save)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_cancel)
                .addGap(12, 12, 12))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lbl_color)
                            .addComponent(lbl_name)
                            .addComponent(lbl_group))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tf_name)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(tf_color)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_choose))
                            .addComponent(combo_panels, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cb_2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbl_audioPath3)
                        .addGap(18, 18, 18)
                        .addComponent(tf_audioPath3, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(btn_browse3, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cb_1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lbl_audioPath1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(tf_audioPath1, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btn_browse1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lbl_audioPath2)
                                .addGap(18, 18, 18)
                                .addComponent(tf_audioPath2, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btn_browse2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jSeparator2)
                    .addComponent(jSeparator3))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_name, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_name))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_color, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_color)
                    .addComponent(btn_choose))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_group)
                    .addComponent(combo_panels, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_audioPath1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_audioPath1)
                    .addComponent(btn_browse1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tf_audioPath2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lbl_audioPath2)
                        .addComponent(btn_browse2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cb_1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_browse3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tf_audioPath3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lbl_audioPath3))
                    .addComponent(cb_2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_cancel)
                    .addComponent(btn_save))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_browse1;
    private javax.swing.JButton btn_browse2;
    private javax.swing.JButton btn_browse3;
    private javax.swing.JButton btn_cancel;
    private javax.swing.JButton btn_choose;
    private javax.swing.JButton btn_save;
    private javax.swing.JCheckBox cb_1;
    private javax.swing.JCheckBox cb_2;
    private javax.swing.JComboBox combo_panels;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JLabel lbl_audioPath1;
    private javax.swing.JLabel lbl_audioPath2;
    private javax.swing.JLabel lbl_audioPath3;
    private javax.swing.JLabel lbl_color;
    private javax.swing.JLabel lbl_group;
    private javax.swing.JLabel lbl_name;
    private javax.swing.JTextField tf_audioPath1;
    private javax.swing.JTextField tf_audioPath2;
    private javax.swing.JTextField tf_audioPath3;
    private javax.swing.JTextField tf_color;
    private javax.swing.JTextField tf_name;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>
}
